package com.example.service.Imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.b_pojo.Musicarticletag;
import com.example.common.b_pojo.Musiccategory;
import com.example.common.b_pojo.Musicuser;
import com.example.common.dto.Acticledto;
import com.example.common.dto.ArticleInfo;
import com.example.common.pojo.musicarticle;
import com.example.common.pojo.musictag;
import com.example.dao.MusicArticleMapper;
import com.example.dao.mapper.BMusicarticletagMapper;
import com.example.dao.mapper.BMusiccategoryMapper;
import com.example.dao.mapper.BMusicuserMapper;
import com.example.service.MusicArticleservice;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MusicArticleserviceImp extends ServiceImpl<MusicArticleMapper, musicarticle> implements MusicArticleservice {

    @Autowired
    private MusicArticleMapper musicArticleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BMusicuserMapper bmusicUserMapper;

    @Autowired
    private BMusiccategoryMapper bmusiccategoryMapper;

    @Autowired
    private BMusicarticletagMapper bMusicarticletagMapper;
    
    /**
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.example.common.dto.Acticledto>
     * @param @param page
	* @param pageSize
	* @param name 根据文章标题查询
	* @param tagid 根据文章标签查询
     * @author znk
     * @date 2024/9/25 17:28
     *
     */
    @Override
    public Page<Acticledto> selectPagearticle(int page, int pageSize, String name, Long tagid) {
        long startTime=System.currentTimeMillis();   //获取开始时间
        Page<Acticledto> page1=new Page<>(page,pageSize);
        Page<Acticledto> page2=null;
        if (tagid == null){
            page2 = musicArticleMapper.selectArticlePage(page1,name);
        }else {
            page2 = musicArticleMapper.selectArticleTagPage(page1,tagid);
        }
        List<Acticledto> records = page2.getRecords();
        for (Acticledto a:records
             ) {
            List<musictag> listtag = musicArticleMapper.listtag(a.getId());
            a.setTaglist(listtag);
        }

        long endTime=System.currentTimeMillis(); //获取结束时间

        System.out.println("程序运行时间： "+(endTime-startTime)+"ms");
        return page2;
    }

    @Override
    public ArticleInfo selectArticleInfo(Long id) {
        ArticleInfo articleInfo = musicArticleMapper.selectArticleInfo(id);
        List<musictag> listtag = musicArticleMapper.listtag(id);
        articleInfo.setTaglist(listtag);
        Double isperfectscore = stringRedisTemplate.boundZSetOps("isperfect").score(String.valueOf(id));
        Double perfectscore = stringRedisTemplate.boundZSetOps("perfect").score(String.valueOf(id));
        articleInfo.setIsperfect((int)Math.round(isperfectscore));
        articleInfo.setPerfect((int)Math.round(perfectscore));
        return articleInfo;
    }

    @Override
    public List<Acticledto> gethasdeletelist(int pageNum, int pageSize, String name, Long tagid,Long categoryId) {
        ModelMapper modelMapper = new ModelMapper();
        Page<musicarticle> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<musicarticle> wapper = new LambdaQueryWrapper<>();
        if(name != null){
            wapper.like(musicarticle::getTitle, name);
        }
        if (categoryId != null){
            wapper.eq(musicarticle::getCategoryId, categoryId);
        }
        if (tagid != null){
            wapper.eq(musicarticle::getCategoryId, tagid);
        }
        Page<musicarticle> page1 = musicArticleMapper.selectPage(page, wapper);
//        将查询到的数据转化为Acticledto，并且根据id查询用户信息，根据id查询标签信息
        Acticledto acticledto = new Acticledto();
        List<musicarticle> records = page1.getRecords();
        // 将 List<musicarticle> 转换为 List<Acticledto>
        List<Acticledto> articleDtos = records.stream()
//                当用户状态为1的时候，被禁用的用户不显示文章
                .filter(article -> {
                    // 检查用户是否存在以及是否被禁用
                    Musicuser musicuser = bmusicUserMapper.selectById(article.getAuthorId());
                    return musicuser != null && !(musicuser.getIsdelete()==1);
                })
                .map(article -> {
                    // 使用 ModelMapper 进行基本属性的复制
                    Acticledto articleDto = modelMapper.map(article, Acticledto.class);
                    // 获取标签列表
                    List<musictag> listtag = musicArticleMapper.listtag(article.getId());
                    articleDto.setTaglist(listtag);
                    // 获取用户信息
                    Musicuser musicuser = bmusicUserMapper.selectById(article.getAuthorId());
                    if (musicuser != null) {
                        articleDto.setUserimg(musicuser.getUserimg());
                        articleDto.setName(musicuser.getName());
                    }
                    return articleDto;
                })
                .collect(Collectors.toList());
        return articleDtos;
    }

    @Override
    public boolean updateCategoryById(Long id, Long categoryId) {
        // 1. 查询 categoryId 是否存在
        Musiccategory musiccategory = bmusiccategoryMapper.selectById(categoryId);
        if (musiccategory == null) {
            // 如果 categoryId 不存在，返回 false
            return false;
        }
        int i=musicArticleMapper.updatecategoryIdById(id, categoryId);
        if (i>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean addTag(Long id, List<Long> tagList) {
        // 检查输入是否有效
        if (id == null || tagList == null || tagList.isEmpty()) {
            return false;
        }
        // 假设 bMusicarticletagMapper 提供了批量插入的方法
        // 这里创建一个 List 来存储所有需要插入的记录
        List<Musicarticletag> tagsToAdd = new ArrayList<>();
        for (Long tagId : tagList) {
            Musicarticletag tag = new Musicarticletag();
            tag.setArticleId(id);
            tag.setTagId(tagId);
            tag.setIsdelete(0);
            tagsToAdd.add(tag);
        }

        int i=bMusicarticletagMapper.batchInsert(tagsToAdd);
        return i>0;
    }

    @Override
    public boolean startandstop(Long id) {
        int i=musicArticleMapper.startandstop(id);
        if (i>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean allremoveById(Long id) {
        if (musicArticleMapper.allremoveById(id)>0){
            return true;
        }
        return false;
    }

    @Override
    public ArticleInfo selectNewArticleInfo(Long id) {
        ArticleInfo articleInfo = musicArticleMapper.selectArticleInfo(id);
        List<musictag> listtag = musicArticleMapper.listtag(id);
        articleInfo.setTaglist(listtag);
        return articleInfo;
    }

    @Override
    public musicarticle selectArticleById(Long id) {
        musicarticle musicarticle = musicArticleMapper.selectById(id);
        if (musicarticle != null){
            return musicarticle;
        }
        return null;
    }


}
